const { PUBLIC_KEY } = require('../app/config')
const errorType = require('../constant/errorType')
const jwt = require('jsonwebtoken')
const verifyAuth = async (ctx, next) => {
  // 1.获取token
  const authorization = ctx.headers.authorization;
  if (!authorization) {
    const error = new Error(errorType.UNAUTHORIZATION);
    return ctx.app.emit('error', error, ctx);
  }
  const token = authorization
  // 2.验证token(id/name/iat/exp)
  try {
    const result = jwt.verify(token, PUBLIC_KEY, {
      algorithms: ["RS256"]
    });
    ctx.user = result;
    console.log(ctx.user);
    await next();
  } catch (err) {
    console.log(err)
    ctx.app.emit('error', new Error(errorType.UNAUTHORIZATION), ctx);
  }
}

module.exports = {
  verifyAuth
}